package com.boot.core.util

import java.io.IOException
import java.security.GeneralSecurityException
import java.security.MessageDigest
import java.util.*
import javax.servlet.http.HttpServletRequest

/**
 * @author rankai
 * createTime 2018-03-2018/3/15 10:56
 */
object ApiSignUtil {

    /**
     * 签名生成算法
     *
     * @param params
     * @param secret
     * @return
     * @throws IOException
     */
    @Throws(IOException::class)
    fun getSignature(params: HashMap<String, String>, secret: String): String {
        // 先将参数以其参数名的字典序升序进行排序
        val sortedParams = TreeMap(params)
        val entrys = sortedParams.entries

        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        val baseString = StringBuilder()
        for ((key, value) in entrys) {
            baseString.append(key).append("=").append(value)
        }
        baseString.append(secret)

        // 使用MD5对待签名串求签
        val bytes: ByteArray
        try {
            val md5 = MessageDigest.getInstance("MD5")
            bytes = md5.digest(baseString.toString().toByteArray(charset("UTF-8")))
        } catch (ex: GeneralSecurityException) {
            throw IOException(ex)
        }

        // 将MD5输出的二进制结果转换为小写的十六进制
        val sign = StringBuilder()
        for (i in bytes.indices) {
            val hex = Integer.toHexString(bytes[i].toInt() and 0xFF)
            if (hex.length == 1) {
                sign.append("0")
            }
            sign.append(hex)
        }
        return sign.toString()
    }

    fun requestMap(request: HttpServletRequest): HashMap<String, String> {
        val map = hashMapOf<String, String>()
        request.parameterMap.apply {
            for (entry in entries) {
                map.put(entry.key, entry.value[0])
            }
        }
        return map
    }

}
